import React from 'react';
import { Link } from 'react-router-dom';
import InputItem from 'antd-mobile/lib/input-item';
import moment from 'moment';
import classNames from 'classnames';
import isArray from 'lodash/isArray';
import localStorage from 'shared/utils/localStorage';
import toFixed from 'shared/utils/toFixed';
import callWeixinJSbridge from 'shared/utils/callWeixinJSbridge';
import { bindCoupon } from 'shared/commonFetch';
import './index.less';

const zhifubao = require('src/static/zhifubao.png');
const weixinzhifu = require('src/static/weixinzhifu.png');

const formatDate = (n) => moment(n * 1000).format("YYYY-MM-DD")

export default class PaymentInfo extends React.PureComponent {
  state = {
    payment_method: '',
    couponType: 1,
    showAlipay: true,
    coupon: {}
  }

  componentDidMount() {
    callWeixinJSbridge(this.weixinPay)
  }

  weixinPay = () => {
    this.setState({ showAlipay: false });
  }

  handleSelectPaymentWay = (value) => {
    this.setState({ payment_method: value });
    this.props.onSelectPayment(value);
  }

  handleCoupon = (item) => {
    const { data } = this.props;
    const { coupon } = this.state;
    if (coupon.coupon_id === item.coupon_id) {
      this.setState({ coupon: {} });
      this.props.onHandleCoupon({});
      return;
    }

    this.totalDiscountFee = 0

    data.productlist.forEach((proItem) => {
      if (item.couponproductids.indexOf(+proItem.product_id) !== -1 && item.type === 'P') {
        proItem.discountFee = this.countDiscount(item, proItem.price * (+proItem.quantity), true)
        this.totalDiscountFee += proItem.discountFee;
      } else {
        proItem.discountFee = '';
      }
    })

    this.setState({ coupon: item });
    this.props.onHandleCoupon(item, data);
  }

  countDiscount = (coupon, price, onlyTypeP = false) => {
    const discount = Number(coupon.discount);
    price = Number(price)

    if (onlyTypeP) {
      return price * (discount / 100);
    } else if (coupon.type === 'P') {
      return this.totalDiscountFee
    }else if(coupon.type === 'F'){
      return discount;
    }

    return 0;
  }

  handleBindcoupon = () => {
    bindCoupon(this.couponCode);
  }

  saveNowLink = () => {
    const { pathname } = __self.history.location
    localStorage.set('nowPaymentPath', pathname)
  }

  render() {
    const { data, charge } = this.props;
    const { payment_method, coupon, showAlipay } = this.state;
    const { lastinvoice = {}, couponlist=[] } = data;
    const invoiceType = {
      '1': '电子发票',
      '2': '增值税专用发票'
    }

    const payTotalFee = Number(toFixed(toFixed(data.totalmoney)) - this.countDiscount(coupon, 0) + Number(toFixed(charge)));
    localStorage.setObject('payRes', {
      totalmoney: payTotalFee
    })

    return (
      <div className="payment-info">
        <div className="payment-info-container">
          <div className="payment-info-invoice">
            <span className="payment-info-lable">发票信息</span>
            <span>
              <Link
                to='/InvoiceForm/electronic-normal-invoice'
                onClick={this.saveNowLink}
              >
                {!isArray(lastinvoice) ?
                  `${invoiceType[lastinvoice.invoice_type]} ${lastinvoice.invoice_info}  ` :
                  '填写发票信息'
                }&gt;
              </Link>

            </span>
          </div>

          <div className="payment-info-coupon">
            <div className="payment-info-lable">优惠抵用</div>
            <div className="payment-info-coupon-content">
              <span
                className={`${this.state.couponType === 1 ? 'conver-active' : ''}`}
                onClick={() => {
                  this.setState({ couponType: 1 })
                  this.props.fetchProductData()
                }}
              >
                优惠卷
              </span>
              <span
                className={`convert-label ${this.state.couponType === 2 ? 'conver-active' : ''}`}
                onClick={() => this.setState({ couponType: 2 })}
              >
                优惠码兑换
              </span>
              {
                this.state.couponType === 1 ?
                  <div className="coupon-list">
                    {
                      couponlist.map((item, index) => (
                        <div
                          key={index}
                          className={classNames("coupon-list-item", {
                            selected: item.coupon_id === coupon.coupon_id
                          })}
                          onClick={()=>this.handleCoupon(item)}
                        >
                          <div className="coupon-list-item-head">
                            <p className="coupon-name">{item.name}</p>
                            <p>有效期至{formatDate(item.date_end)}</p>
                          </div>
                          <div className="coupon-list-item-body">
                            <p>限产品</p>
                          </div>
                        </div>
                      ))
                    }
                  </div>
                  :
                  <div>
                    <div className="input-label">请输入优惠卷兑换码</div>
                    <div className="redeem-code">
                      <InputItem
                        onChange={(value)=>{this.couponCode = value}}
                      />
                      <button className="redeem-code-button" onClick={this.handleBindcoupon}>兑换</button>
                    </div>
                  </div>
              }

            </div>
          </div>
        </div>
        <div className="payment-subtract">
          <span>金额抵用</span>
          <span>￥{toFixed(this.countDiscount(coupon, 0))}</span>
        </div>
        <div className="payment-info-container payment-type">
          <div className="payment-info-lable">支付方式</div>
          <div className="payment-way">
            <div
              className={classNames('payment-way-weixin', { active: payment_method === 'weixin' })}
              onClick={() => {this.handleSelectPaymentWay('weixin')}}
            >
              <img src={weixinzhifu} alt='' />
            </div>
            {
              showAlipay &&
              <div
                className={classNames('payment-way-zhifubao', { active: payment_method === 'alipay' })}
                onClick={() => {this.handleSelectPaymentWay('alipay')}}
              >
                <img src={zhifubao} alt='' />
              </div>
            }
          </div>
        </div>

        <div className="payment-summary">
          <div className="payment-summary-item">
            <span className="payment-info-lable">商品金额</span>
            <span >¥{toFixed(data.totalmoney)}</span>
          </div>
          <div className="payment-summary-item">
            <span className="payment-info-lable">促销立减</span>
            <span >¥{toFixed(this.countDiscount(coupon, 0))}</span>
          </div>
          <div className="payment-summary-item">
            <span className="payment-info-lable">运费</span>
            <span >¥{toFixed(charge)}</span>
          </div>
          <div className="payment-total-prices">
            <span>总价:</span>
            <span >¥{toFixed(payTotalFee)}</span>
          </div>
          <div className="report-button">
            <span className="button" onClick={this.props.onSubmit}>去结算</span>
          </div>
        </div>
      </div>
    )
  }
}

